import requests
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from bs4 import BeautifulSoup
import time
import random

class SSQAnalyzer:
    def __init__(self):
        self.data_url = "http://www.cwl.gov.cn/ygkj/wqgg/"
        self.data_file = "ssq_history.csv"
        self.history_data = None

    def fetch_history_data(self, start_page=1, end_page=10):
        """从中国福彩网获取历史数据"""
        print("正在获取历史数据...")
        results = []
        
        for page in range(start_page, end_page + 1):
            try:
                url = f"{self.data_url}?pageNo={page}"
                headers = {
                    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
                }
                response = requests.get(url, headers=headers, timeout=10)
                response.encoding = "utf-8"
                
                soup = BeautifulSoup(response.text, "html.parser")
                table = soup.find("table", class_="result_table")
                if not table:
                    print(f"第{page}页未找到数据表格")
                    continue
                
                rows = table.find_all("tr")[1:]
                for row in rows:
                    cols = row.find_all("td")
                    if len(cols) < 8:
                        continue
                    
                    issue = cols[0].text.strip()  # 期号
                    date = cols[1].text.strip()  # 日期
                    red_balls = [col.text.strip() for col in cols[2:7]]  # 红球
                    blue_ball = cols[7].text.strip()  # 蓝球
                    
                    results.append({
                        "issue": issue,
                        "date": date,
                        "red_balls": red_balls,
                        "blue_ball": blue_ball
                    })
                
                print(f"已获取第{page}页数据")
                time.sleep(random.uniform(1, 3))  # 避免请求过快
            except Exception as e:
                print(f"获取第{page}页数据失败: {e}")
                continue
        
        if results:
            self.history_data = pd.DataFrame(results)
            self.history_data.to_csv(self.data_file, index=False)
            print(f"数据已保存至{self.data_file}")
        else:
            print("未获取到任何数据")
        
        return self.history_data

    def load_history_data(self):
        """从本地文件加载历史数据"""
        try:
            self.history_data = pd.read_csv(self.data_file)
            print(f"已从{self.data_file}加载历史数据")
            return True
        except FileNotFoundError:
            print(f"未找到数据文件{self.data_file}，请先调用fetch_history_data方法获取数据")
            return False

    def analyze_red_balls(self):
        """分析红球出现频率"""
        if self.history_data is None:
            if not self.load_history_data():
                return
        
        # 统计每个红球出现的次数
        red_ball_counts = {str(i).zfill(2): 0 for i in range(1, 34)}
        
        for _, row in self.history_data.iterrows():
            red_balls = row["red_balls"].strip("[]").split(", ")
            for ball in red_balls:
                red_ball_counts[ball] += 1
        
        # 转换为DataFrame以便排序和展示
        red_ball_df = pd.DataFrame({
            "ball": list(red_ball_counts.keys()),
            "count": list(red_ball_counts.values())
        })
        
        # 按出现次数排序
        red_ball_df = red_ball_df.sort_values(by="count", ascending=False)
        
        print("红球出现频率Top 10:")
        print(red_ball_df.head(10))
        
        return red_ball_df

    def analyze_blue_balls(self):
        """分析蓝球出现频率"""
        if self.history_data is None:
            if not self.load_history_data():
                return
        
        # 统计每个蓝球出现的次数
        blue_ball_counts = {str(i).zfill(2): 0 for i in range(1, 17)}
        
        for _, row in self.history_data.iterrows():
            blue_ball = row["blue_ball"]
            blue_ball_counts[blue_ball] += 1
        
        # 转换为DataFrame以便排序和展示
        blue_ball_df = pd.DataFrame({
            "ball": list(blue_ball_counts.keys()),
            "count": list(blue_ball_counts.values())
        })
        
        # 按出现次数排序
        blue_ball_df = blue_ball_df.sort_values(by="count", ascending=False)
        
        print("蓝球出现频率Top 10:")
        print(blue_ball_df.head(10))
        
        return blue_ball_df

    def predict_next_ssq(self, method="frequency"):
        """预测下一期双色球号码
           method: "frequency"(基于频率)或"random"(随机生成)
        """
        print(f"使用{method}方法预测下一期双色球号码...")
        
        if method == "frequency":
            # 基于频率预测
            red_ball_df = self.analyze_red_balls()
            blue_ball_df = self.analyze_blue_balls()
            
            # 选择出现频率最高的6个红球
            predicted_red_balls = red_ball_df.head(6)["ball"].tolist()
            predicted_red_balls.sort()
            
            # 选择出现频率最高的1个蓝球
            predicted_blue_ball = blue_ball_df.head(1)["ball"].tolist()[0]
        else:
            # 随机生成
            predicted_red_balls = sorted([str(random.randint(1, 33)).zfill(2) for _ in range(6)])
            predicted_blue_ball = str(random.randint(1, 16)).zfill(2)
        
        print(f"预测的红球: {', '.join(predicted_red_balls)}")
        print(f"预测的蓝球: {predicted_blue_ball}")
        
        return {
            "red_balls": predicted_red_balls,
            "blue_ball": predicted_blue_ball
        }

    def visualize_data(self):
        """可视化历史数据"""
        if self.history_data is None:
            if not self.load_history_data():
                return
        
        # 红球频率可视化
        red_ball_df = self.analyze_red_balls()
        plt.figure(figsize=(12, 6))
        plt.bar(red_ball_df["ball"], red_ball_df["count"])
        plt.title("红球出现频率")
        plt.xlabel("红球号码")
        plt.ylabel("出现次数")
        plt.xticks(rotation=90)
        plt.tight_layout()
        plt.savefig("red_ball_frequency.png")
        print("红球频率图已保存为red_ball_frequency.png")
        
        # 蓝球频率可视化
        blue_ball_df = self.analyze_blue_balls()
        plt.figure(figsize=(12, 6))
        plt.bar(blue_ball_df["ball"], blue_ball_df["count"])
        plt.title("蓝球出现频率")
        plt.xlabel("蓝球号码")
        plt.ylabel("出现次数")
        plt.xticks(rotation=90)
        plt.tight_layout()
        plt.savefig("blue_ball_frequency.png")
        print("蓝球频率图已保存为blue_ball_frequency.png")

# 使用示例
if __name__ == "__main__":
    analyzer = SSQAnalyzer()
    
    # 首次运行需要获取数据
    # analyzer.fetch_history_data(start_page=1, end_page=50)
    
    # 加载已有数据
    if analyzer.load_history_data():
        # 分析数据
        analyzer.analyze_red_balls()
        analyzer.analyze_blue_balls()
        
        # 预测下一期
        analyzer.predict_next_ssq(method="frequency")
        
        # 可视化数据
        analyzer.visualize_data()